﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NewsMine.DomainObjects;
using NewsDiscoveryEngine;
using NewsMine.Storage;
using WebApp1.Models;
using NewsMine.Utilities;

namespace WebApp1.Controllers
{
    [AdminAuthorizeAttribute]
    public class WebSiteInfoController : Controller
    {
        //
        // GET: /WebSiteInfo/

        public ActionResult Index()
        {
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;

                int count = webSiteKVStore.GetCount();

                var websiteObjects = webSiteKVStore.Get(0, count + 1);

                var webSites = new List<WebSiteInfo>();

                foreach (var websiteInfoObject in websiteObjects)
                {
                    WebSiteInfo wbSiteInfo = (WebSiteInfo)websiteInfoObject;
                    //if (wbSiteInfo.MenuItemconfigs != null && wbSiteInfo.MenuItemconfigs.Count > 0)
                    webSites.Add(wbSiteInfo);
                }


                return View(webSites);
            }
            catch (Exception ex)
            {
                throw ex; //todo: needs to be handled.
            }
        }

        //
        // GET: /WebSiteInfo/Details/5

        public ActionResult Details(string id)
        {
            return View();
        }


        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Create(WebSiteInfo webSiteInfo)
        {
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;
                webSiteKVStore.Set(webSiteInfo.Domain, webSiteInfo);
                webSiteKVStore.Close();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                throw ex; //todo: needs to be handled.
            }
        }

        public ActionResult Delete(string id)
        {
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;
                var webObject = webSiteKVStore.Get(id); // here id is domain.
                if (webObject != null)
                    webSiteKVStore.Delete(id);

                webSiteKVStore.Close();

            }
            catch (Exception ex)
            {
                return Content("Error while deleting.... " + id + " " + ex.Message);
                //todo: needs tobe logged for this error scenario.  

            }
            return Content(id + " is Successfuly deleted.");
        }


        public ActionResult TagMenu(string id)
        {
            string menuUrl = Request.QueryString.Get("menuurl");
            string tag = Request.QueryString.Get("tag");

            
               
            if (string.IsNullOrEmpty(tag))
                return Content("menuurl is the required parameter to perform menu delete action");

            tag = tag.ToLower();

            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;
                var webObject = webSiteKVStore.Get(id); // here id is domain.
                if (webObject != null)
                {
                    WebSiteInfo wb = (WebSiteInfo)webObject;
                    menuUrl = HttpUtility.UrlDecode(menuUrl);


                    //var resultedMenus = (from mnu in wb.MenuItemconfigs
                    //                     where mnu.Url.ToLower() == menuUrl.ToLower()
                    //                     select mnu).ToList<WebSiteMenu>();

                    //wb.MenuItemconfigs = resultedMenus;

                    if (string.IsNullOrEmpty(menuUrl))
                    {
                        AddTagToWebSite(wb, tag);

                    }
                    else if (wb.MenuItemconfigs != null && wb.MenuItemconfigs.Count > 0)
                    {

                        for (int i = 0; i < wb.MenuItemconfigs.Count; i++)
                        {
                            var mnuItem = wb.MenuItemconfigs[i];

                            if (mnuItem.Url.ToLower() == menuUrl.ToLower())
                            {
                                AddTagToMenu(mnuItem, tag);
                            }
                        }
                    }
                    webSiteKVStore.Replace(wb.Domain, wb);

                    webSiteKVStore.Close();
                }
                else
                {
                    return Content("Domain is the required parameter to perform menu tag action or there could be chance of not finding the passed domain the repository.");
                }
            }
            catch (Exception ex)
            {
                return Content("Error while tagging menu item.... " + id + " " + ex.Message);
                //todo: needs tobe logged for this error scenario.  

            }
            return Content("Tagging Menu item is done successfuly.");
        }

        private void AddTagToWebSite(WebSiteInfo wb, string tag)
        {
            if (wb.Tags == null || wb.Tags.Count == 0)
            {
                wb.Tags = new List<string>();
                wb.Tags.Add(tag.ToLower());
            }
            else
            {
                if (wb.Tags.Contains(tag) == false)
                    wb.Tags.Add(tag);
            }
        }

        private void AddTagToMenu(WebSiteMenu mnuItem, string tag)
        {
            if (mnuItem.Tags == null || mnuItem.Tags.Count == 0)
            {
                mnuItem.Tags = new List<string>();
                mnuItem.Tags.Add(tag.ToLower());
            }
            else
            {
                if (mnuItem.Tags.Contains(tag) == false)
                    mnuItem.Tags.Add(tag);
            }
        }

     
        public ActionResult DeleteMenu(string id)
        {
            string menuUrl = Request.QueryString.Get("menuurl");

            if (string.IsNullOrEmpty(menuUrl))
                return Content("menuurl is the required parameter to perform menu delete action");
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;
                var webObject = webSiteKVStore.Get(id); // here id is domain.
                if (webObject != null)
                {
                    WebSiteInfo wb = (WebSiteInfo)webObject;
                    menuUrl = HttpUtility.UrlDecode(menuUrl);


                    var resultedMenus = (from mnu in wb.MenuItemconfigs
                                         where mnu.Url.ToLower() != menuUrl.ToLower()
                                         select mnu).ToList<WebSiteMenu>();

                    wb.MenuItemconfigs = resultedMenus;

                    webSiteKVStore.Replace(wb.Domain, wb);

                    webSiteKVStore.Close();
                }
                else
                {
                    return Content("Domain is the required parameter to perform menu delete action or there could be chance of not finding the passed domain the repository.");
                }
            }
            catch (Exception ex)
            {
                return Content("Error while deleting menu item.... " + id + " " + ex.Message);
                //todo: needs tobe logged for this error scenario.  

            }
            return Content("Menu item is Successfuly deleted.");
        }

        public ActionResult Edit(string id)
        {
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;

                var webObject = webSiteKVStore.Get(id); // here id is domain.

                return View(webObject);
            }
            catch (Exception ex)
            {
                Response.Write("<h1>Error</h1><br/>");
                Response.Write(ex.Message + "<br/>" + ex.StackTrace);

                return Content("Error");
                //throw ex; //todo: needs to be handled.
            }
        }

        [HttpPost]
        public ActionResult Edit(string id, string TagsList, WebSiteInfo webSiteInfoFromBrowser)
        {
            try
            {
                var webSiteKVStore = Defaults.WebSiteInfoMasterStore;

                var webObject = (WebSiteInfo)webSiteKVStore.Get(id);

                //todo: Include required fields...

                webObject.Name = webSiteInfoFromBrowser.Name;
                webObject.LocalName = webSiteInfoFromBrowser.LocalName;
                webObject.Language = webSiteInfoFromBrowser.Language;
                webObject.FrequencyOfUpdates = webSiteInfoFromBrowser.FrequencyOfUpdates;
                webObject.IsActive = webSiteInfoFromBrowser.IsActive;
                webObject.IsAdultContentSite = webSiteInfoFromBrowser.IsAdultContentSite;
                webObject.HomePageUrl = webSiteInfoFromBrowser.HomePageUrl;
                webObject.Description = webSiteInfoFromBrowser.Description;
                webObject.Logo1Uri = webSiteInfoFromBrowser.Logo1Uri;
                webObject.Rank = webSiteInfoFromBrowser.Rank;
                webObject.AlexaRank = webSiteInfoFromBrowser.AlexaRank;

                webObject.Tags = new List<string>();

                string[] tags = TagsList.Split('#');

                foreach (var tg in tags)
                {
                    if (!string.IsNullOrEmpty(tg))
                        webObject.Tags.Add(tg);
                }


                webSiteKVStore.Replace(id, webObject);
                webSiteKVStore.Close();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                throw ex; //todo: needs to be handled.
            }
        }


        public ActionResult AddTagToFeed(string feedid, string tag)
        {
            long feedIdLong = Convert.ToInt64(feedid);

            FeedItem feedItem = FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.GetFeedItemByID(feedIdLong);

            if (feedItem == null)
            {
                return Content("feed could not be found");
            }

            if (feedItem.Tags == null || feedItem.Tags.Count == 0)
            {
                feedItem.Tags = new List<string>();
                feedItem.Tags.Add(tag.ToLower());
            }
            else
            {
                if (feedItem.Tags.Contains(tag) == false)
                    feedItem.Tags.Add(tag);
            }

            feedItem.UpdatedDateTime = DateTime.UtcNow;
            feedItem.Sanitize();
            FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.AddFeedToStore(feedItem);

            return Content(string.Join(",", feedItem.Tags.ToArray()));

        }

        public ActionResult DeleteFeedById(string feedid)
        {
            long feedIdLong = Convert.ToInt64(feedid);

            FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.DeleteByID(feedIdLong);
            FeedIndexer.Instance.DeleteFeedItemsByID(feedIdLong);
            
            return Content("Feed is deleted.");

        }

        public ActionResult DeleteFeedByDomain(string domain)
        {
            if (string.IsNullOrEmpty(domain))
                return Content("Invalid domain is supplied; please supply proper domain name to delete");

            domain = domain.ToLower();

            FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.DeleteByDomain(domain);
            FeedIndexer.Instance.DeleteFeedItemsByDomain(domain);

            return Content("Add Feeds is deleted  from domain " + domain + ".");
        }

        public ActionResult RemoveTagFromFeed(string feedid, string tag)
        {
            long feedIdLong = Convert.ToInt64(feedid);

            FeedItem feedItem = FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.GetFeedItemByID(feedIdLong);

            if (feedItem == null)
            {
                return Content("feed could not be found");
            }

            if (feedItem.Tags == null || feedItem.Tags.Count == 0)
            {
                return Content("notags");
            }
            else
            {
                if (feedItem.Tags.Contains(tag) == true)
                    feedItem.Tags.Remove(tag);
                else
                    return Content("tag not found");
            }

            feedItem.UpdatedDateTime = DateTime.UtcNow;

            feedItem.Sanitize();

            FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.AddFeedToStore(feedItem);

            return Content(string.Join(",", feedItem.Tags.ToArray()));

        }

        public ActionResult AddKeyWord(string category, string keyword)
        {
            try
            {
                NewsMine.DataManagers.KeyWordManager.AddKeyWordsToCategory(category,keyword);
            }
            catch (Exception ex)
            {
                TempLogger.Log("Exception while adding keyword", ex);

                return Content("Error while adding keyword" + ex.Message);
            }

            return Content("Success");
        }


    }
}
